//
//  HMTabBar.swift
//  SinaWeibo
//
//  Created by 统杰李 on 16/7/19.
//  Copyright © 2016年 统杰李. All rights reserved.
//

import UIKit

class HMTabBar: UITabBar {

    
    //加号按钮点击要执行的闭包
    
    var composeButtonClickClosure: (()->())?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        addSubview(composeButton)
    }

    // 关键点：下面的代码里面抛了一个错
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    

    // MARK: -布局
    override func layoutSubviews() {
        super.layoutSubviews()
        
        composeButton.center = CGPoint(x:self.frame.width/2, y: self.frame.height/2)
        
        //调整其他按钮的位置
        //每一个按钮的宽度
        let itemW = self.frame.width / 5
        
        // 当前遍历到的  UITabBarButton 的位置
        var index = 0
        for value in subviews {
            
            if value.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                
                //设置宽度
                value.frame.size.width = itemW
                value.frame.origin.x = CGFloat(index) * itemW
                
                index++
                
                if index == 2 {
                    
                    index++
                }
                
            }
            
        }

    }

    // MARK: -监听方法
    func composeButtonClick(){
        
        composeButtonClickClosure?()
        
    }
    
    
    // MARK: -懒加载控件
    
    private lazy var composeButton: UIButton = {
       let button = UIButton()
        
        //监听按钮点击
        button.addTarget(self, action: "composeButtonClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        //设置不同状态下的图片
        button.setImage(UIImage(named: "tabbar_compose_icon_add_highlighted"), forState: UIControlState.Highlighted)
        
        button.setImage(UIImage(named: "tabbar_compose_icon_add"), forState: UIControlState.Normal)
        
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button_highlighted"), forState: UIControlState.Selected)
        
        button.setBackgroundImage(UIImage(named:"tabbar_compose_button"), forState: UIControlState.Normal)
        
        button.sizeToFit()
       
        return button
    }()
    
    

}
